﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Data.Util;
using JNPF.Utils;
using System.Collections;
using System.Data;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 数据同步
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018.09.03
    /// </summary>
    internal class DbSyncService : DataFactory, DbSyncIService
    {
        /// <summary>
        /// 批量写入
        /// </summary>
        /// <param name="linkFrom">数据库连接 From</param>
        /// <param name="linkTo">数据库连接To</param>
        /// <param name="table">表</param>
        public async Task ImportTableData(DbLinkEntity linkFrom, DbLinkEntity linkTo, string table)
        {
            try
            {
                DataTable tableData = new DataTable();
                #region 取同步数据
                var dbTypeFrom = linkFrom == null ? DatabaseType.SqlServer : linkFrom.DbType.ToDatabaseType();
                var connectionStringFrom = DataHelper.ToConnectionString(linkFrom.DbType.ToDatabaseType(), linkFrom.Host, linkFrom.Port, linkFrom.UserName, linkFrom.Password, linkFrom.ServiceName);
                var strSqlFrom = "SELECT * FROM " + table;
                var db = linkFrom == null ? this.Basic : this.Data(connectionStringFrom, dbTypeFrom);
                using (db)
                {
                    tableData = await db.GetTableSqlAsync(strSqlFrom);
                }
                #endregion

                #region 插入同步数据
                var dbTypeTo = linkFrom == null ? DatabaseType.SqlServer : linkTo.DbType.ToDatabaseType();
                var connectionStringTo = DataHelper.ToConnectionString(linkTo.DbType.ToDatabaseType(), linkTo.Host, linkTo.Port, linkTo.UserName, linkTo.Password, linkTo.ServiceName);
                using (db = this.Data(connectionStringTo, linkTo.DbType.ToDatabaseType()))
                {
                    await db.BeginTransactionAsync();
                    foreach (DataRow dr in tableData.Rows)
                    {
                        Hashtable ht = dr.ToHashtable();
                        var strSql = DbSqlBuilder.InsertSql(table, ht);
                        var parameter = DbSqlBuilder.ToDbParameter(ht, db.dbContext.dbType);
                        await db.ExecuteSqlAsync(strSql.ToString(), parameter);
                    }
                    await db.CommitTransactionAsync();
                }
                #endregion
            }
            catch (global::System.Exception ex)
            {
                throw;
            }
        }
    }
}
